/* eslint no-unused-vars:0 */
import React, { Component } from 'react';
import Axios from 'axios';
import {
    Modal,
    Button,
    Menu,
    Col,
    Row,
    Icon,
    Input,
    Select,
    Table,
    Pagination,
    Spin
} from 'antd';
import 'whatwg-fetch';
import WrappedAddRiskFormForm from './AddForm';
import WrappedUpdateRiskFormForm from './UpdateForm';
import './index.less';
import { Link } from 'react-router-dom';
import PageComponent from './pageComponent.jsx';

const Search = Input.Search;
const Option = Select.Option;

class ManageRisk extends Component {
    state = {
        ////////
        ModalText: 'Content of the modal',
        visible: false,
        visibleUpdate: false,
        deleteRiskVisible: false,
        deleteRiskID: '',
        updateRiskId: 'null',
        confirmLoading: false,
        confirmLoadingUpdate: false,
        riskTypes: [{ id: '123', type: '网络忙' }],
        riskLevels: [{ id: '123', type: '网络忙' }],
        searchTypeInput: '',
        searchLevelInput: '',
        // 更新回显表单
        title: '',
        content: '',
        mediaType: '',
        fromMedia: '',
        fromAuthor: '',
        forward: '',
        follow: '',
        tipFlag: '',
        url: '',
        dealStatus: '',

        visibleError: false,

        indexList: [], // 获取数据的存放数组
        totalNum: '', // 总记录数
        totalData: [],
        current: 1, //当前页码
        pageSize: 5, //每页显示的条数5条
        goValue: '',
        totalPage: '', //总页数
        columns: [
            {
                title: '风险种类',
                dataIndex: 'riskType.type',
                width: 120,
                className: 'blodFont'
            },
            {
                title: '预警级别',
                dataIndex: 'riskLevel.level',
                className: 'blodFont',
                width: 120,
                render: (text) => (
                    <span
                        className={
                            text == '特重'
                                ? 'tableColRed'
                                : text == '较重'
                                ? 'tableColBlue'
                                : text == '较强'
                                ? 'tableColYellow'
                                : 'tableColGrey'
                        }>
                        {text}
                    </span>
                )
            },
            {
                title: '内容',
                dataIndex: 'url',
                width: 200,
                render: (text, record) => (
                    <a href={text} target="_blank" rel="noopener noreferrer">
                        {record.title}
                    </a>
                )
            },
            {
                title: '发生时间',
                dataIndex: 'createTime',
                width: 120,
                render: (text) => <span>{this.$changeTimeToString(text)}</span>
            },
            {
                title: '处理状态',
                dataIndex: 'dealStatus.status',
                width: 120,
                className: 'blodFont'
            },
            {
                title: '事件ID',
                dataIndex: 'id',
                width: 150,
                render: (text) => <span>{text}</span>
            }
        ]
    };

    //点击翻页
    pageClick(pageNum) {
        var _this = this; //如果不定义就会出现作用域的问题this.setState不是一个函数
        if (pageNum != _this.state.current) {
            _this.state.current = pageNum;
        }

        _this.state.indexList = []; //清空之前的数据

        let temp = {
            type: _this.state.searchTypeInput,
            level: _this.state.searchLevelInput,
            pageSize: _this.state.pageSize,
            pageNum: _this.state.current - 1
        };

        console.log(_this.state.searchTypeInput);
        console.log(_this.state.searchLevelInput);
        console.log(temp);
        this.$get('/risk/findRisks', temp)
            .then((res) => {
                console.log(res);
                if (res) {
                    ///
                    _this.setState({ totalData: res.pages.content });
                    _this.setState({ totalNum: res.pages.totalElements });
                    //计算总页数= 总记录数 / 每页显示的条数
                    let totalPage = Math.ceil(
                        _this.state.totalNum / _this.state.pageSize
                    );
                    _this.setState({ totalPage: totalPage });

                    _this.state.indexList = []; //清空之前的数据
                    for (var i = 0; i < _this.state.pageSize; i++) {
                        if (_this.state.totalData[i]) {
                            _this.state.indexList.push(
                                _this.state.totalData[i]
                            );
                        }
                    }
                    _this.setState({ indexList: _this.state.indexList });
                }
            })
            .catch((e) => {
                console.log('error');
            });
    }

    //上一步
    goPrevClick() {
        var _this = this;
        let cur = this.state.current;
        if (cur > 1) {
            _this.pageClick(cur - 1);
        }
    }

    //下一步
    goNext() {
        var _this = this;
        let cur = _this.state.current;
        //alert(cur+"==="+_this.state.totalPage)
        if (cur < _this.state.totalPage) {
            _this.pageClick(cur + 1);
        }
    }

    // 跳转到指定页
    goSwitchChange(e) {
        var _this = this;
        _this.setState({ goValue: e.target.value });
        var value = e.target.value;
        // alert(value+"==="+_this.state.totalPage)
        if (!/^[1-9]\d*$/.test(value)) {
            alert('页码只能输入大于1的正整数');
        } else if (parseInt(value) > parseInt(_this.state.totalPage)) {
            alert('没有这么多页');
        } else {
            _this.pageClick(value);
        }
    }

    handleAddRisk(data) {
        this.setState({
            visible: true
        });
    }

    handleUpdateRiskVis(data) {
        // /findRisk
        console.log(this.state.updateRiskId);
        console.log('哦哦');
        // riskId
        let addParam = {
            riskId: this.state.updateRiskId
        };

        this.$get('/risk/findRisk', addParam)
            .then((res) => {
                console.log(res);
                this.setState({
                    title: res.risk.title,
                    content: res.risk.content,
                    mediaType: res.risk.mediaType,
                    fromMedia: res.risk.fromMedia,
                    fromAuthor: res.risk.fromAuthor,
                    forward: res.risk.forward,
                    follow: res.risk.follow,
                    tipFlag: res.risk.tipFlag,
                    url: res.risk.url,
                    dealStatus: res.risk.dealStatus.status,
                    visibleUpdate: true,
                    visibleError: false
                });
            })
            .catch((e) => {
                console.log(e);
                this.setState({
                    visibleError: true
                });

                return;
            });

        /* this.setState({
            visibleUpdate: true,
        });*/
    }

    // ================================  //
    handleUpdateRisk(data) {
        this.setState({
            // updateRiskId: data,
        });
    }

    onChangeDeleteRiskInput(data) {
        if (data) {
            this.setState({
                deleteRiskID: data.target.value
            });
        } else {
            this.setState({
                deleteRiskID: ''
            });
        }
    }

    // onChangeUpdateRiskInput
    onChangeUpdateRiskInput(data) {
        if (data) {
            this.setState({
                updateRiskId: data.target.value
            });
        } else {
            this.setState({
                updateRiskId: ''
            });
        }
    }

    handleDeleteRisk(data) {
        let deleteRiskid = {
            riskId: this.state.deleteRiskID
        };
        this.$get('/risk/deleteRisk', deleteRiskid)
            .then((res) => {
                this.setState({
                    deleteRiskID: ''
                });
            })
            .catch((e) => {
                console.log(e);
            });
        this.setState({
            deleteRiskVisible: true
        });
    }

    handleDeleteRiskCancel = () => {
        this.setState({
            deleteRiskVisible: false
        });
    };
    handleDeleteRiskOk = () => {
        ////////
        this.setState({
            deleteRiskVisible: false
        });
    };

    // ================================  //
    handleOk = (e) => {
        //点击对话框OK按钮触发的事件
        console.log();

        let demo = this.refs.getFormVlaue; //通过refs属性可以获得对话框内form对象
        demo.validateFields((err, values) => {
            if (!err) {
                console.log(values); //这里可以拿到数据
                let addParam = {
                    title: values.title,
                    type: values.type.label,
                    level: values.level.label,
                    content: values.content,
                    mediaType: values.mediaType,
                    fromMedia: values.fromMedia,
                    fromAuthor: values.fromAuthor,
                    forward: values.forward,
                    follow: values.follow,
                    tipFlag: values.tipFlag,
                    url: values.url
                };
                this.$post('/risk/addRisk', addParam)
                    .then((res) => {
                        this.setState({});
                    })
                    .catch((e) => {
                        console.log(e);
                    });
                //
                this.setState({
                    ModalText: 'The modal will be closed after two seconds',
                    confirmLoading: false,
                    visible: false,
                    deleteRiskVisible: true
                });
                // 上面的代码可以忽略
                //
            } else {
                this.setState({
                    ModalText: 'The modal will be closed after two seconds',
                    confirmLoading: false,
                    visible: true,
                    deleteRiskVisible: false
                });
            }
        });
    };

    // ================================  //
    handleUpdateOk = (e) => {
        //点击对话框OK按钮触发的事件
        console.log('更新喽');

        let demo = this.refs.getFormVlaue; //通过refs属性可以获得对话框内form对象
        demo.validateFields((err, values) => {
            if (!err) {
                console.log(values); //这里可以拿到数据
                let addParam = {
                    title: values.title,
                    type: values.type.label,
                    level: values.level.label,
                    content: values.content,
                    mediaType: values.mediaType,
                    fromMedia: values.fromMedia,
                    fromAuthor: values.fromAuthor,
                    forward: values.forward,
                    follow: values.follow,
                    tipFlag: values.tipFlag,
                    url: values.url
                };
                this.$post(
                    '/risk/updateRisk?riskId=' +
                        this.state.updateRiskId +
                        '&status=' +
                        values.status.label,
                    addParam
                )
                    .then((res) => {
                        this.setState({});
                    })
                    .catch((e) => {
                        console.log(e);
                    });
                //
                this.setState({
                    ModalText: 'The modal will be closed after two seconds',
                    confirmLoadingUpdate: false,
                    visible: false,
                    deleteRiskVisible: true,
                    visibleUpdate: false,
                    updateRiskId: ''
                });
                // 上面的代码可以忽略
                //
            } else {
                this.setState({
                    ModalText: 'The modal will be closed after two seconds',
                    confirmLoadingUpdate: false,
                    visible: false,
                    deleteRiskVisible: true,
                    visibleUpdate: false,
                    updateRiskId: ''
                });
            }
        });
    };

    handleErrorOk = () => {
        console.log('Clicked cancel button');
        this.setState({
            visibleError: false
        });
    };

    handleErrorCancel = () => {
        console.log('Clicked cancel button');
        this.setState({
            visibleError: false
        });
    };
    handleCancel = () => {
        //点击取消按钮触发的事件

        console.log('Clicked cancel button');
        this.setState({
            visible: false
        });
    };

    handleUpdateCancel = () => {
        //点击取消按钮触发的事件
        console.log('Clicked cancel button');
        this.setState({
            visibleUpdate: false
        });
    };

    findRiskTypes() {
        this.$get('/risk/findAllRiskTypes')
            .then((res) => {
                this.setState({
                    riskTypes: res.riskTypes
                });
            })
            .catch((e) => {
                console.log(e);
            });
    }

    findLevelTypes() {
        this.$get('/risk/findAllRiskLevels')
            .then((res) => {
                this.setState({
                    riskLevels: res.riskLevels
                });
            })
            .catch((e) => {
                console.log(e);
            });
    }

    handleChangeLevel(e) {
        if (e) {
            this.setState({
                searchLevelInput: e.label
            });
        } else {
            this.setState({
                searchLevelInput: ''
            });
        }
    }

    handleChangeType(e) {
        if (e) {
            this.setState({
                searchTypeInput: e.label
            });
        } else {
            this.setState({
                searchTypeInput: ''
            });
        }
    }

    handleClickForSearch() {
        this.pageClick(this.state.current);
    }

    componentWillMount() {
        this.pageClick(1);
        this.findRiskTypes();
        this.findLevelTypes();
    }

    render() {
        const {
            deleteRiskVisible,
            visible,
            confirmLoading,
            ModalText
        } = this.state;
        return (
            <div className="myDiv">
                <Row className="row1">
                    <div>
                        <Modal
                            title="删除预警事件"
                            visible={deleteRiskVisible}
                            onOk={this.handleDeleteRiskOk}
                            okText={'确认'}
                            onCancel={this.handleDeleteRiskCancel}
                            cancelText={'取消'}>
                            操作成功,请刷新页面
                        </Modal>
                    </div>
                    <Input
                        className={'ant-input'}
                        placeholder="输入风险事件ID以删除"
                        allowClear
                        onChange={this.onChangeDeleteRiskInput.bind(this)}
                    />
                    <Button
                        type="danger"
                        onClick={this.handleDeleteRisk.bind(this)}>
                        删除
                    </Button>
                    <Input
                        className={'ant-input'}
                        placeholder="输入风险事件ID以编辑"
                        allowClear
                        onChange={this.onChangeUpdateRiskInput.bind(this)}
                    />
                    <Button
                        type="danger"
                        onClick={this.handleUpdateRiskVis.bind(this)}>
                        编辑
                    </Button>
                    <Button
                        type="primary"
                        onClick={this.handleAddRisk.bind(this)}>
                        添加预警事件
                    </Button>

                    <div style={{ float: 'right' }}>
                        <Select
                            className="sub-row2-select"
                            labelInValue
                            defaultValue={{ key: '请选择风险类型' }}
                            style={{
                                width: 150,
                                height: 30,
                                marginRight: '20px'
                            }}
                            onChange={this.handleChangeType.bind(this)}
                            allowClear>
                            {this.state.riskTypes.map((item) => {
                                return (
                                    <Option key={item.id} value={item.id}>
                                        {item.type}
                                    </Option>
                                );
                            })}
                        </Select>
                        <Select
                            className="sub-row2-select"
                            labelInValue
                            defaultValue={{ key: '请选择预警级别' }}
                            style={{ width: 150, height: 30 }}
                            onChange={this.handleChangeLevel.bind(this)}
                            allowClear>
                            {this.state.riskLevels.map((item) => {
                                return (
                                    <Option
                                        key={item.id}
                                        value={item.id}
                                        className={
                                            item.level == '特重'
                                                ? 'tableRowRed'
                                                : item.level == '较重'
                                                ? 'tableRowOrange'
                                                : item.level == '较强'
                                                ? 'tableRowYellow'
                                                : 'tableRowBlue'
                                        }>
                                        {item.level}
                                    </Option>
                                );
                            })}
                        </Select>
                        <Button
                            type="primary"
                            icon="search"
                            shape="circle"
                            onClick={this.handleClickForSearch.bind(this)}
                        />
                    </div>

                    <br />
                    <Row className="sub-row2">
                        <Table
                            className="emergency-table"
                            columns={this.state.columns}
                            dataSource={this.state.indexList}
                            pagination={false}
                        />
                        ,
                        <div style={{ float: 'right' }}>
                            <PageComponent
                                total={this.state.totalNum}
                                current={this.state.current}
                                totalPage={this.state.totalPage}
                                goValue={this.state.goValue}
                                pageClick={this.pageClick.bind(this)}
                                goPrev={this.goPrevClick.bind(this)}
                                goNext={this.goNext.bind(this)}
                                switchChange={this.goSwitchChange.bind(this)}
                            />
                        </div>
                    </Row>
                    <Modal
                        title="添加预警事件"
                        visible={visible}
                        onOk={this.handleOk}
                        okText={'确认'}
                        confirmLoading={confirmLoading}
                        onCancel={this.handleCancel}
                        cancelText={'取消'}>
                        <WrappedAddRiskFormForm ref="getFormVlaue" />
                    </Modal>

                    <Modal
                        title="更改预警事件"
                        visible={this.state.visibleUpdate}
                        onOk={this.handleUpdateOk}
                        okText={'确认'}
                        confirmLoading={this.state.confirmLoadingUpdate}
                        onCancel={this.handleUpdateCancel}
                        cancelText={'取消'}>
                        <WrappedUpdateRiskFormForm
                            ref="getFormVlaue"
                            title={this.state.title}
                            content={this.state.content}
                            mediaType={this.state.mediaType}
                            fromMedia={this.state.fromMedia}
                            fromAuthor={this.state.fromAuthor}
                            forward={this.state.forward}
                            follow={this.state.follow}
                            tipFlag={this.state.tipFlag}
                            url={this.state.url}
                        />
                    </Modal>
                </Row>
            </div>
        );
    }
}

export default ManageRisk;
